package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.afollestad.materialcamera.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.PathEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.entities.beans.CollectInfo;
import com.sam.im.heiqun.entities.beans.DownloadInfo;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.MediaUtil;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.dialogs.ItemSelectorDialog;
import com.sam.im.heiqun.utils.FileUtil;
import com.sam.im.heiqun.utils.JsonUtil;
import com.sam.im.heiqun.utils.PathUtil;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.StringUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by lzf on 2016/9/2.
 * http://ocgig6vo9.bkt.clouddn.com/Wildlife.wmv
 */
public class PlayActivity extends BaseActivity {
    private VideoView videoView;//视频
    protected String videoUrl = "";
    private RelativeLayout controller, relativeLayout;//控制面板  动画载体
    private SeekBar seekBar;//控制面板 进度条
    //    private boolean flag=true;
    private TextView current, total;//当前时间 总时间
    private long lastPosition = 0;//
    //    private AnimationDrawable animationDrawable;//动画
    private Thread thread;
    private ImageView img_play;
    private ImageView img_loading;
    private VedioEntity vedioEntity;
    private RelativeLayout containerView;
    private CollectInfo collectInfo;

    public static Intent newIntent(Context context, String videoUrl, VedioEntity vedioEntity, CollectInfo collectInfo) {
        Intent intent = new Intent(context, PlayActivity.class);
        intent.putExtra("videoUrl", videoUrl);
        intent.putExtra("vedioEntity", vedioEntity);
        intent.putExtra("collectInfo", collectInfo);
        return intent;
    }

    @Override
    public int getContentViewId() {
        return R.layout.qiniu_activity_play;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        vedioEntity = getIntent().getParcelableExtra("vedioEntity");
        collectInfo = getIntent().getParcelableExtra("collectInfo");
        this.initVideoPlay();
    }

    public void restart(View view) {
        //播放过 才可以重新开始
        Log.e("lzf_video", "重新开始");
        if (videoView != null && videoView.getCurrentPosition() > 0) {
            videoView.seekTo(0);
//            flag=true;
            videoView.start();
        }
    }

    public void start(View view) {
        Log.e("lzf_video", "开始");
        //只有不是播放状态才可以start
        if (videoView != null && !videoView.isPlaying()) {
            videoView.start();
        }
    }

    public void pause(View view) throws InterruptedException {
        //正在播放 暂停
        Log.e("lzf_video", "暂停");
        if (videoView != null && videoView.isPlaying()) {
            videoView.pause();
        }
    }

    private void initVideoPlay() {
        if (getIntent() != null && getIntent().getStringExtra("videoUrl") != null && !getIntent().getStringExtra("videoUrl").equals("")) {
            videoUrl = getIntent().getStringExtra("videoUrl");
        }
        videoView = (VideoView) findViewById(R.id.videoView);
//        //动画
//        ImageView imageView = (ImageView) findViewById(R.id.image);
        //返回
        controller = (RelativeLayout) findViewById(R.id.controller);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        current = (TextView) findViewById(R.id.current);
        total = (TextView) findViewById(R.id.total);
        img_play = (ImageView) findViewById(R.id.record_play);
        img_play.setEnabled(false);
        img_loading = (ImageView) findViewById(R.id.img_loading);
        containerView = findViewById(R.id.relative);
        Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_loading);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        if (operatingAnim != null) {
            img_loading.startAnimation(operatingAnim);
        }
        img_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoView != null) {
                    videoView.start();
                    img_play.setVisibility(View.GONE);
                }
            }
        });
//        animationDrawable= (AnimationDrawable) imageView.getDrawable();
        if (videoUrl != null && !videoUrl.equals("")) {
            videoView.setVideoURI(Uri.parse(videoUrl));
            videoView.start();
//            if (animationDrawable!=null&&!animationDrawable.isRunning()) {
//                animationDrawable.start();
//            }
        } else {
            Toast.makeText(PlayActivity.this, "视频地址错误", Toast.LENGTH_SHORT).show();
        }
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        if (videoView != null && seekBar != null) {
                            if (videoView.isPlaying()) {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (videoView.getCurrentPosition() != 0 && videoView.getCurrentPosition() != lastPosition) {
                                    Log.e("lzf_thread", "CurrentPosition  " + videoView.getCurrentPosition() + "");
                                    seekBar.setProgress(videoView.getCurrentPosition());
                                    lastPosition = videoView.getCurrentPosition();
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();
       /* thread=new Thread(new Runnable() {
            @Override
            public void run() {
                *//*try {
                    while (true){
                        if (videoView!=null&&seekBar!=null) {
                            if (videoView.isPlaying()) {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (videoView.getCurrentPosition() != 0 && videoView.getCurrentPosition() != lastPosition) {
                                    Log.e("lzf_thread", "CurrentPosition  " + videoView.getCurrentPosition() + "");
                                    seekBar.setProgress(videoView.getCurrentPosition());
                                    lastPosition = videoView.getCurrentPosition();
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }*//*
            }
        });*/
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {//视屏加载完毕
                img_loading.setVisibility(View.GONE);
                img_loading.clearAnimation();
                Log.e("lzf_onPrepared", videoView.getWidth() + " " + videoView.getHeight() + "  " + videoView.getRotation());
                //设置seekBar和总时间
                if (videoView.getDuration() != 0) {
                    seekBar.setMax(videoView.getDuration());
                    total.setText(setTime(videoView.getDuration() / 1000));
                }
                new Thread(runnable).start();

            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
//                flag=false;
                //Log.e("lzf_Completion","播放完成");

                img_play.setEnabled(true);
                img_play.setVisibility(View.VISIBLE);
                seekBar.setProgress(videoView.getDuration());
                Log.e("lzf_Completion", videoView.getWidth() + " " + videoView.getHeight() + "  " + videoView.getRotation());
            }
        });
        //根据seekBar的进度 更新当前时间
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (current != null) {
                    current.setText(setTime(progress / 1000));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
//                videoView.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (videoView != null) {
                    videoView.seekTo(seekBar.getProgress());
                    videoView.start();
                }
            }
        });

        containerView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                if (vedioEntity != null && !vedioEntity.isCanForward()) {
                    return false;
                }
                ItemSelectorDialog<ItemSelectorDialog.Entity> dialog = new ItemSelectorDialog<>(v.getContext());
                dialog.setTitle(null);
                List<ItemSelectorDialog.Entity> itemTextList = new ArrayList<>();
                itemTextList.add(new ItemSelectorDialog.Entity(v.getResources().getString(com.sam.im.heiqun.R.string.send_to_friends)));
                itemTextList.add(new ItemSelectorDialog.Entity(v.getResources().getString(com.sam.im.heiqun.R.string.baocunshipin)));
                if (collectInfo != null) {
                    itemTextList.add(new ItemSelectorDialog.Entity(v.getResources().getString(com.sam.im.heiqun.R.string.collection)));
                }
                ItemSelectorDialog.Entity[] items = new ItemSelectorDialog.Entity[itemTextList.size()];
                itemTextList.toArray(items);
                dialog.setItems(items);
                dialog.setDialogClickListener(new ItemSelectorDialog.DialogItemClickListener<ItemSelectorDialog.Entity>() {
                    @Override
                    public void confirm(int position, ItemSelectorDialog.Entity result) {
                        if (getResources().getString(com.sam.im.heiqun.R.string.send_to_friends).equals(result.getText())) {

                            UserEntivity userEntivity = ToolsUtils.getUser();

                            final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_VEDIO, UUID.randomUUID().toString(),
                                    Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_MAM, 0, JsonUtil.toJson(vedioEntity), Constant.MESSAGE_TYPR_VEDIO,
                                    System.currentTimeMillis(), System.currentTimeMillis(), 0, JsonUtil.toJson(new PathEntivity(vedioEntity.getVedioPath(), vedioEntity.getVedioBitmappath())), ToolsUtils.getMyUserId() + "_" + "", 0, userEntivity.getHeadUrl());

                            Bundle bundle = new Bundle();
                            bundle.putSerializable("msg", imMessage);
                            bundle.putInt("tag", 11);

                            Intent intent = new Intent(PlayActivity.this, SelecteLocalFriendActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else if (getResources().getString(com.sam.im.heiqun.R.string.baocunshipin).equals(result.getText())) {

                            if (videoUrl == null) {
                                return;
                            }
                            File file = new File(videoUrl);
                            if (file.exists()) {
                                String fileName = StringUtils.makeFileName(videoUrl);
                                if (TextUtils.isEmpty(fileName)) {
                                    showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                    return;
                                }
                                final File saveFile = new File(PathUtil.getVideoDir(), fileName);
                                try {
                                    FileUtil.copyFile(file, saveFile);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                }
                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_success) + ":" + saveFile.getAbsolutePath());
                                MediaUtil.refreshMediaFileStore(PlayActivity.this, saveFile.getAbsolutePath(), null);
                                return;
                            }
                            String fileName = StringUtils.makeFileName(vedioEntity.getVedioUrl());
                            if (TextUtils.isEmpty(fileName)) {
                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                return;
                            }
                            final File saveFile = new File(PathUtil.getVideoDir(), fileName);
                            RxJavaUtil.download(vedioEntity.getVedioUrl(), saveFile).compose(RxJavaUtil.<DownloadInfo>applySchedules())
                                    .compose(PlayActivity.this.<DownloadInfo>bindLifeCycle())
                                    .compose(PlayActivity.this.<DownloadInfo>applyProgress(getResources().getString(com.sam.im.heiqun.R.string.saving)))
                                    .subscribe(new AbsAPICallback<DownloadInfo>() {
                                        @Override
                                        public void onNext(DownloadInfo downloadInfo) {
                                            if (downloadInfo.isFinish()) {
                                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_success) + ":" + saveFile.getAbsolutePath());
                                                MediaUtil.refreshMediaFileStore(PlayActivity.this, saveFile.getAbsolutePath(), null);
                                            }
                                        }

                                        @Override
                                        protected void onResultError(ApiException ex) {
                                            showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                        }
                                    });
                        } else if (getResources().getString(com.sam.im.heiqun.R.string.collection).equals(result.getText())) {

                            PGService.getInstance().addcolaction(collectInfo.getCategory(),
                                    collectInfo.getUrl(),
                                    collectInfo.getContent(),
                                    collectInfo.getFromname(),
                                    ToolsUtils.getMyUserId(),
                                    collectInfo.getFromid())
                                    .compose(PlayActivity.this.<ValidateEntivity>applyProgress(null))
                                    .subscribe(new AbsAPICallback<ValidateEntivity>() {
                                        @Override
                                        protected void onResultError(ApiException ex) {
                                            if (ex != null) {
                                                String displayMessage = ex.getDisplayMessage();
                                                try {
                                                    JSONObject object = new JSONObject(displayMessage);
                                                    JSONObject data = object.getJSONObject("data");
                                                    String info = data.getString("info");
                                                    ToolsUtils.showToast(PlayActivity.this, info);
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onNext(ValidateEntivity validateEntivity) {
                                            if (validateEntivity != null) {
                                                ToolsUtils.showToast(PlayActivity.this, validateEntivity.getInfo());
                                            }
                                        }
                                    });
                        }
                    }
                });
                dialog.show();
                return true;
            }
        });
    }

    public String setTime(long time) {
        if (time < 60) {
            if (time < 10) {
                return "00:00:0" + time;
            } else {
                return "00:00:" + time;
            }
        } else if (time < 3600) {
            if (time < 600) {
                if (time % 60 < 10) {
                    return "00:0" + time / 60 + ":0" + time % 60;
                } else {
                    return "00:0" + time / 60 + ":" + time % 60;
                }
            } else {
                if (time % 60 < 10) {
                    return "00:" + time / 60 + ":0" + time % 60;
                } else {
                    return "00:" + time / 60 + ":" + time % 60;
                }
            }
        } else {
            //小于10小时
            if (time < 36000) {
                //0+time/3600:  时
                if (time % 3600 < 600) {
                    if (time % 60 < 10) {
                        return "0" + time / 3600 + ":0" + time / 60 + ":0" + time % 60;
                    } else {
                        return "0" + time / 3600 + ":0" + time / 60 + ":" + time % 60;
                    }
                } else {
                    if (time % 60 < 10) {
                        return "0" + time / 3600 + ":" + time / 60 + ":0" + time % 60;
                    } else {
                        return "0" + time / 3600 + ":" + time / 60 + ":" + time % 60;
                    }
                }
            } else {
                if (time % 3600 < 600) {
                    if (time % 60 < 10) {
                        return time / 3600 + ":0" + time / 60 + ":0" + time % 60;
                    } else {
                        return time / 3600 + ":0" + time / 60 + ":" + time % 60;
                    }
                } else {
                    if (time % 60 < 10) {
                        return time / 3600 + ":" + time / 60 + ":0" + time % 60;
                    } else {
                        return time / 3600 + ":" + time / 60 + ":" + time % 60;
                    }
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (thread != null && thread.isAlive()) {
                thread.interrupt();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (img_loading != null) {
            img_loading.clearAnimation();
        }
    }


}
